package www.hszw.search.domain.service;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import www.hszw.search.base.entiy.ElasticEntity;
import www.hszw.search.base.service.BaseElasticService;
import www.hszw.search.domain.entity.Good;
import www.hszw.search.domain.mapper.GoodMapper;

import java.util.List;
import java.util.Map;

/**
 *
 */
@Service
public class GoodEsService {

    @Autowired
    GoodMapper goodMapper;

    @Autowired
    BaseElasticService elasticService;

    /**
     * 同步数据到es
     */
    public void sync(String idxName,int pageNum,int pageSize) throws Exception {
        boolean isExist = elasticService.isExistsIndex(idxName);
        if(!isExist){
            return;
        }
        Page page = PageHelper.startPage(pageNum,pageSize);
        Map<String,Object> param = Maps.newHashMap();
        List<Good> goodList = goodMapper.queryList(param);
        if(goodList != null && !goodList.isEmpty()){
            List<ElasticEntity> elasticEntities = Lists.newArrayList();
            for(Good good : goodList){
                ElasticEntity entity = new ElasticEntity();
                entity.setId(good.getGoodId().toString());
                Map<String,Object> goodMap = JSON.parseObject(JSON.toJSONString(good), Map.class);
                entity.setData(goodMap);
                elasticEntities.add(entity);
            }
            elasticService.insertBatch(idxName,elasticEntities);
        }
        if(page.getPages() != pageNum){
            sync(idxName,++pageNum,pageSize);
        }else{
            return;
        }
    }

    public void queryGood(){
        Page page = PageHelper.startPage(1,10);
        Map<String,Object> param = Maps.newHashMap();
        List<Good> goodList = goodMapper.queryList(param);
        int pages = page.getPages();
        System.out.println(page.toString());
    }

}
